<template>
  <el-form :inline="true" class="demo-form-inline ">
    <div style="display: flex; justify-content: center;align-items: center;">
      <el-form-item>
        <el-button type="success" @click="addDialogShow=true">添加</el-button>
      </el-form-item>
      <el-form-item label="名称" style="float: right;">
        <el-input v-model="condition.name" placeholder="请输入要搜索的商品名称" @input="selectByPage(1)"/>
      </el-form-item>
      <el-form-item label="描述" style="float: right;">
        <el-input v-model="condition.dscp" placeholder="请输入要搜索的商品描述" @input="selectByPage(1)"/>
      </el-form-item>
    </div>
    <div style="display: flex; justify-content: center;align-items: center;">
      <el-form-item label="是否上下架" style="float: right;">
        <el-select v-model="condition.status"
                   placeholder="请输入要上下架的商品"
                   clearable
                   :value-on-clear="null"
                   style="width: 200px"
                   @change="selectByPage(1)">
          <el-option label="上架商品" value="1"/>
          <el-option label="下架商品" value="0"/>
        </el-select>
      </el-form-item>
      <el-form-item label="根据父分类" style="float: right;">
        <el-select v-model="condition.parentId"
                   placeholder="请输入要查询的父分类"
                   clearable
                   :value-on-clear="null"
                   style="width: 200px"
                   @change="selectByPage(1)">
          <el-option label="大类" value="0"/>
          <el-option v-for="(parent,index) in allParent"
                     :key="index"
                     :label="parent.name"
                     :value="parent.id"/>
        </el-select>
      </el-form-item>
    </div>
  </el-form>

  <el-table :data="pageInfo.list" style="width: 100%">
    <el-table-column prop="id" label="ID"/>
    <el-table-column prop="name" label="名称"/>
    <el-table-column prop="pic" label="图片">
      <template #default="scope">
        <el-avatar :size="55" :src="SERVER_ADDR+'/category/pic/' + scope.row.pic"/>
      </template>
    </el-table-column>
    <el-table-column prop="dscp" label="描述"/>
    <el-table-column prop="tpoint" label="父分类">
      <template #default="scope">
        <el-tag type="success" v-if="scope.row.parent">{{ scope.row.parent.name }}</el-tag>
      </template>
    </el-table-column>

    <!--<el-table-column prop="tpoint" label="是否推荐">-->
    <!--  <template #default="scope">-->
    <!--    <el-tag type="warning" v-if="scope.row.recom===0">不推荐</el-tag>-->
    <!--    <el-tag type="success" v-if="scope.row.recom===1">推荐</el-tag>-->
    <!--  </template>-->
    <!--</el-table-column>-->
    <el-table-column label="使用状态">
      <template #default="scope">
        <el-switch
            v-model="scope.row.recom"
            inline-prompt
            style="--el-switch-off-color: #13ce66; --el-switch-on-color: #ff4949"
            active-text="不推荐"
            inactive-text="推荐"
            :active-value="0"
            :inactive-value="1"
            @change="updateRecom(scope.row.id,scope.row.recom)"
        />
      </template>
    </el-table-column>

    <!--<el-table-column prop="tpoint" label="是否上架">-->
    <!--  <template #default="scope">-->
    <!--    <el-tag type="warning" v-if="scope.row.status===0">下架</el-tag>-->
    <!--    <el-tag type="success" v-if="scope.row.status===1">上架</el-tag>-->
    <!--  </template>-->
    <!--</el-table-column>-->
    <el-table-column label="使用状态">
      <template #default="scope">
        <el-switch
            v-model="scope.row.status"
            inline-prompt
            style="--el-switch-off-color: #13ce66; --el-switch-on-color: #ff4949"
            active-text="下架"
            inactive-text="上架"
            :active-value="0"
            :inactive-value="1"
            @change="updateStatus(scope.row.id,scope.row.status)"
        />
      </template>
    </el-table-column>

    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="primary" :icon="Edit" color="blue" @click="selectById(scope.row.id)"/>
        <el-popconfirm title="你确认要删除嘛" confirm-button-text="确认" cancel-button-text="取消" width="200px"
                       @confirm="deleteCategory(scope.row.id)">
          <template #reference>
            <!--<el-button type="primary" :icon="Delete" color="red" @click="console.log(scope.row.tid)"-->
            <!--           v-if="scope.row.estate == 2" disabled/>-->
            <el-button type="primary" :icon="Delete" color="red" @click="console.log(scope.row.id)"/>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <el-row class="row-bg" justify="center">
    <el-pagination background layout="prev, pager, next"
                   v-model:current-page="pageInfo.pageNum"
                   :page-count="pageInfo.pages"
                   @update:current-page="selectByPage"
                   style="margin-top: 50px;"/>
  </el-row>

  <!-- 添加商品的对话框开始 -->
  <el-dialog v-model="addDialogShow" title="新增分类" width="500">
    <el-form label-width="20%">
      <el-form-item label="名称">
        <el-input autocomplete="off" v-model="categoryAdd.name" style="width: 300px"/>
      </el-form-item>
      <!-- action：请求的URL地址 name: 上传的文件字段名-->
      <el-form-item label="图片">
        <el-upload class="avatar-uploader" :action="SERVER_ADDR+'/category/upload'" name="pic"
                   :headers="headers"
                   :show-file-list="false" :on-success="handleAvatarSuccessAdd" :before-upload="beforeAvatarUpload">
          <img v-if="categoryAdd.pic" :src="SERVER_ADDR+'/category/pic/'+categoryAdd.pic" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="描述">
        <el-input autocomplete="off" v-model="categoryAdd.dscp" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="父分类ID">
        <!-- el-select中v-model的值最终选择的元素的的值
            label-显示/看
            value - option的值，选择了哪个option，那么v-model的值就和被选中的这个option的value值相同-->
        <el-select v-model="categoryAdd.parentId"
                   placeholder="请选择所属父类"
                   :value-on-clear="null"
                   clearable
                   :empty-values="[0]"
                   style="width: 300px">
          <el-option v-for="(category, index) in allParent" :key="index" :label="category.name" :value="category.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="是否推荐">
        <el-radio-group v-model="categoryAdd.recom" style="width: 300px">
          <el-radio :value="1" size="large">推荐</el-radio>
          <el-radio :value="0" size="large">不推荐</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否上架">
        <el-radio-group v-model="categoryAdd.status" style="width: 300px">
          <el-radio :value="1" size="large">上架</el-radio>
          <el-radio :value="0" size="large">不上架</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogShow = false">取消</el-button>
        <el-button @click="insert()">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 添加商品的对话框结束 -->
  <!-- 修改商品的对话框开始 -->
  <el-dialog v-model="updateDialogShow" title="修改分类" width="500">
    <el-form label-width="20%">
      <el-form-item label="名称">
        <el-input autocomplete="off" v-model="categoryUpdate.name" style="width: 300px"/>
      </el-form-item>
      <!-- action：请求的URL地址 name: 上传的文件字段名-->
      <el-form-item label="图片">
        <el-upload class="avatar-uploader" :action="SERVER_ADDR+'/category/upload'" name="pic"
                   :headers="headers"
                   :show-file-list="false" :on-success="handleAvatarSuccessUpdate" :before-upload="beforeAvatarUpload">
          <img v-if="categoryUpdate.pic" :src="SERVER_ADDR+'/category/pic/'+categoryUpdate.pic" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="描述">
        <el-input autocomplete="off" v-model="categoryUpdate.dscp" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="父分类ID">
        <!-- el-select中v-model的值最终选择的元素的的值
            label-显示/看
            value - option的值，选择了哪个option，那么v-model的值就和被选中的这个option的value值相同-->
        <el-select v-model="categoryUpdate.parentId"
                   placeholder="请选择所属父类"
                   :value-on-clear="null"
                   clearable
                   :empty-values="[0]"
                   style="width: 300px">
          <el-option v-for="(category, index) in allParent" :key="index" :label="category.name" :value="category.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="是否推荐">
        <el-radio-group v-model="categoryUpdate.recom" style="width: 300px">
          <el-radio :value="1" size="large">推荐</el-radio>
          <el-radio :value="0" size="large">不推荐</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否上架">
        <el-radio-group v-model="categoryUpdate.status" style="width: 300px">
          <el-radio :value="1" size="large">上架</el-radio>
          <el-radio :value="0" size="large">不上架</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateDialogShow = false">取消</el-button>
        <el-button @click="update()">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 修改商品的对话框结束 -->
</template>

<script setup>
import {computed, ref} from 'vue';
import {Delete, Edit, Search, Share, Upload} from '@element-plus/icons-vue'
import {ElMessage, ElLoading} from 'element-plus';
import categoryApi from "@/api/categoryApi.js";

import { useTokenStore } from '@/stores/token.js';//使用store
const tokenStore = useTokenStore();
//解决加了拦截器添加修改时上传图片传不上去的问题
const headers=computed(()=>{
  const token= tokenStore.tokenStr;
  return{
    token:token
  }
})

//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR)
//搜索条件
const condition = ref({
  name: null,
  dscp: null,
  parentId: null,
  status: null,
});
//分页信息
const pageInfo = ref({
  pages: 0,
  pageSize: 0,
  pageNum: 0,
})
const addDialogShow = ref(false)//操作新增的弹框出现
const categoryAdd = ref({//被添加父类子类商品的信息
  name: null,
  dscp: null,
  pic: null,
  parentId: 0,
  recom: 1,
  status: 1,
});
const updateDialogShow = ref(false);//操作修改的弹框出现
const categoryUpdate = ref({//被添加父类子类商品的信息
  id: null,
  name: null,
  dscp: null,
  pic: null,
  parentId: 0,
  recom: 1,
  status: 1,
});
const allParent = ref([])//所有的父分类
//上传图片之前的回调
function beforeAvatarUpload(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片仅支持JPG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}
//成功添加上传图片之后的回调
function handleAvatarSuccessAdd(resp, uploadFile) {
  //console.log(resp);
  if (resp.code == 10000) {
    ElMessage.success(resp.msg)
    categoryAdd.value.pic = resp.data
  } else {
    ElMessage.error(resp.msg)
  }
}
//成功修改上传头像之后的回调
function handleAvatarSuccessUpdate(resp, uploadFile) {
  console.log(resp);
  if (resp.code == 10000) {
    ElMessage.success(resp.msg)
    categoryUpdate.value.pic = resp.data
  } else {
    ElMessage.error(resp.msg)
  }
}

//确认添加数据
function insert() {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  categoryApi.insert(categoryAdd.value)
      .then(resp => {
        loading.close()
        //判断---弹出消息--刷新表格
        if (resp.code == 10000) {
          //弹出消息
          ElMessage.success(resp.msg)
          //隐藏
          addDialogShow.value = false
          //清空
          categoryAdd.value = {
            name: null,
            dscp: null,
            pic: null,
            parentId: 0,
            recom: "1",
            status: "1",
          }
        } else {
          //弹出消息
          ElMessage.error(resp.msg)
        }
        //刷新表格
        selectByPage(1)
      })
}

//确定删除数据
function deleteCategory(id) {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  categoryApi.delete(id)
      .then(resp => {
        loading.close()
        //判断---弹出消息--刷新表格
        if (resp.code == 10000) {
          //弹出消息
          ElMessage.success(resp.msg)
        } else {
          //弹出消息
          ElMessage.error(resp.msg)
        }
        //刷新表格
        selectByPage(1)
      })

}

//定义根据id查询方法查询分类信息，回显数据
function selectById(id) {
  categoryApi.selectById(id)
      .then(resp => {
        console.log(resp);
        categoryUpdate.value = resp.data
        //展示修改模态框
        updateDialogShow.value = true;
      })
}
//按钮修改recom
function updateRecom(id,recom){
  categoryApi.update({id,recom})
      .then(resp=>{
        if (resp.code === 10000) {
          ElMessage.success(resp.msg)
        } else {
          ElMessage.error(resp.msg)
        }
        selectByPage(pageInfo.value.pageNum)
      })
}
//按钮修改status
function updateStatus(id,status){
  categoryApi.update({id,status})
      .then(resp=>{
        if (resp.code === 10000) {
          ElMessage.success(resp.msg)
        } else {
          ElMessage.error(resp.msg)
        }
        selectByPage(pageInfo.value.pageNum)
      })
}
//确认修改数据
function update() {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  categoryApi.update(categoryUpdate.value)
      .then(resp => {
        loading.close()
        //判断---弹出消息--刷新表格
        if (resp.code === 10000) {
          //弹出消息
          ElMessage.success(resp.msg)
          //隐藏
          updateDialogShow.value = false
        } else {
          //弹出消息
          ElMessage.error(resp.msg)
        }
        selectByPage(pageInfo.value.pageNum)
      })
}
function selectByPage(pageNum) {
  categoryApi.selectByPage(condition.value, pageNum, 4)
      .then(resp => {
        pageInfo.value = resp.data
        //console.log(resp.data)
      })
}

//获取所有的父分类
function selectAllParent() {
  categoryApi.selectAllParent()
      .then(resp => {
        console.log(resp.data)
        allParent.value = resp.data
      })
}

selectAllParent()
selectByPage(1)
</script>

<style scoped>
.avatar-uploader,
.avatar {
  width: 200px;
  height: 160px;
  display: block;
  border: 2px dotted #dcdfe6;
  border-radius: 5px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 160px;
  text-align: center;
}
</style>